/**
 * 全局消息服务
 * 可以在组件内外使用的消息提示服务
 */
import { ref } from 'vue'

// 消息类型定义
export type MessageType = 'success' | 'error' | 'warning' | 'info'

// 消息接口
export interface MessageInstance {
  success: (message: string) => void
  error: (message: string) => void
  warning: (message: string) => void
  info: (message: string) => void
}

// 全局消息实例引用
const globalMessageInstance = ref<MessageInstance | null>(null)

/**
 * 设置全局消息实例
 * 在应用的根组件中调用，传入 naive-ui 的 message 实例
 */
export function setGlobalMessageInstance(instance: MessageInstance): void {
  globalMessageInstance.value = instance
}

/**
 * 获取全局消息实例
 */
export function getGlobalMessageInstance(): MessageInstance | null {
  return globalMessageInstance.value
}

/**
 * 默认的消息实现（使用 console）
 */
const defaultMessageInstance: MessageInstance = {
  success: (message: string) => console.log(`[SUCCESS] ${message}`),
  error: (message: string) => console.error(`[ERROR] ${message}`),
  warning: (message: string) => console.warn(`[WARNING] ${message}`),
  info: (message: string) => console.info(`[INFO] ${message}`)
}

/**
 * 全局消息服务
 * 自动使用已设置的消息实例，如果没有设置则使用默认实现
 */
export const globalMessage: MessageInstance = {
  success: (message: string) => {
    const instance = globalMessageInstance.value || defaultMessageInstance
    instance.success(message)
  },
  error: (message: string) => {
    const instance = globalMessageInstance.value || defaultMessageInstance
    instance.error(message)
  },
  warning: (message: string) => {
    const instance = globalMessageInstance.value || defaultMessageInstance
    instance.warning(message)
  },
  info: (message: string) => {
    const instance = globalMessageInstance.value || defaultMessageInstance
    instance.info(message)
  }
}

// 导出默认实例，供直接使用
export default globalMessage